import { h, defineComponent, ref } from 'vue'
import { DownloadOutlined, SearchOutlined } from '@vicons/antd'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NIcon,
  NCard,
  NSpace,
  NPagination,
  useMessage
} from 'naive-ui'
import {
  deleteSQLManage,
  getSQLManageList
} from '@/service/modules/integration-sqlmanage'
import styles from './index.module.scss'
import edit from './edit'
import * as XLSX from 'xlsx'

const sqlmanage = defineComponent({
  name: 'sqlmanage',
  components: {
    edit
  },
  setup() {
    const sqlForm = ref({
      typeMetaData: 'hive',
      sql: ''
    })

    const sqlSearch = () => {
      pagination.value.page = 1
      handleList()
    }

    const createColumns = ref([])

    const sqlList = ref([])

    const pagination = ref({
      pageSize: 10,
      pageCount: 0,
      page: 1,
      showQuickJumper: true,
      pageSizes: [10, 30, 50],
      showSizePicker: true,
      loading: false,
      onUpdatePage: (page: number) => {
        pagination.value.page = page
        handleList()
      },
      onUpdatePageSize: (pageSize: number) => {
        pagination.value.pageSize = pageSize
        pagination.value.page = 1
        handleList()
      }
    })

    const handleList = function () {
      pagination.value.loading = true
      const temp = {
        ...sqlForm.value,
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      }
      getSQLManageList(temp)
        .then((res: any) => {
          if (res.data.query && res.data.query[0]) {
            // @ts-ignore
            const tempColumns = []
            Object.keys(res.data.query[0]).forEach((item) => {
              tempColumns.push({
                title: item,
                key: item,
                minWidth: 200
              })
            })
            tempColumns.push({
              title: '操作',
              key: 'actions',
              fixed: 'right',
              minWidth: 200,
              render(row: any) {
                return h(
                  NSpace,
                  {},
                  {
                    default: () => {
                      return [
                        h(
                          NButton,
                          {
                            size: 'small',
                            disabled:
                              sqlForm.value.sql.indexOf('.ods_') > -1
                                ? true
                                : false,
                            onClick: () => {
                              itemData.value = row
                              sessionStorage.setItem(
                                'sqlmanageEditData',
                                JSON.stringify(itemData.value)
                              )
                              editClick()
                            }
                          },
                          { default: () => '编辑' }
                        ),
                        h(
                          NButton,
                          {
                            size: 'small',
                            disabled:
                              sqlForm.value.sql.indexOf('.ods_') > -1
                                ? true
                                : false,
                            onClick: () => {
                              deleteSQLManage({
                                ...sqlForm.value,
                                oldData: row
                                // @ts-ignore
                              })
                                // @ts-ignore
                                .then((res) => {
                                  // eslint-disable-next-line no-console
                                  console.log(res)
                                  message.success('删除成功')
                                  handleList()
                                })
                                .catch((err: any) => {
                                  message.error(
                                    err.msg ? err.msg : '接口未知错误'
                                  )
                                  pagination.value.loading = false
                                })
                            }
                          },
                          { default: () => '删除' }
                        )
                      ]
                    }
                  }
                )
              }
            })
            // @ts-ignore
            createColumns.value = tempColumns
          }
          sqlList.value = res.data.query
          pagination.value.pageCount = Math.ceil(
            res.data.total / pagination.value.pageSize
          )
          pagination.value.loading = false
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
          pagination.value.loading = false
        })
    }

    const message = useMessage()

    const editModal = ref(false)

    const editClick = function () {
      editModal.value = true
    }

    const handleModal = function (refush = false) {
      editModal.value = false
      if (refush) {
        handleList()
      }
    }

    const itemData = ref()

    let temp = {}

    const sqlExport = function () {
      if (createColumns.value.length <= 1) {
        message.warning('暂无数据')
        return false
      }
      temp = createColumns.value[createColumns.value.length - 1]

      createColumns.value.pop()
      setTimeout(() => {
        const workbook = XLSX.utils.table_to_book(
          document.getElementById('table')
        ) //需要在table上定义一个id
        try {
          XLSX.writeFile(workbook, 'BOX信息.xlsx')
          message.success('导出成功!')
        } catch (e) {
          message.error('导出失败!')
        }
      }, 500)
      setTimeout(() => {
        // @ts-ignore
        createColumns.value.push(temp)
      }, 1000)
    }

    return {
      sqlForm,
      sqlSearch,
      sqlList,
      columns: createColumns,
      pagination,
      handleList,
      message,
      handleModal,
      editModal,
      editClick,
      itemData,
      sqlExport
    }
  },
  render() {
    return (
      <div>
        <NSpace vertical>
          <NCard size='small'>
            <NForm model={this.sqlForm}>
              <NFormItem path='sql' label='SQL查询'>
                <NInput
                  v-model:value={this.sqlForm.sql}
                  type='textarea'
                  placeholder='SQL查询'
                ></NInput>
              </NFormItem>
              <NButton onClick={this.sqlSearch}>
                <NIcon>
                  <SearchOutlined />
                </NIcon>
                查询
              </NButton>
              <NButton onClick={this.sqlExport}>
                <NIcon>
                  <DownloadOutlined />
                </NIcon>
                导出
              </NButton>
            </NForm>
          </NCard>
          <NCard size='small'>
            <NSpace vertical>
              <NDataTable
                // @ts-ignore
                id={'table'}
                // @ts-ignore
                columns={this.columns}
                data={this.sqlList}
                loading={this.pagination.loading}
                scroll-x='1500'
                min-height='160'
              ></NDataTable>
              <NPagination
                class={styles['page-position']}
                display-order={['quick-jumper', 'pages', 'size-picker']}
                page-count={this.pagination.pageCount}
                page-size={this.pagination.pageSize}
                page-sizes={this.pagination.pageSizes}
                page={this.pagination.page}
                on-update:page={this.pagination.onUpdatePage}
                on-update:page-size={this.pagination.onUpdatePageSize}
                show-quick-jumper
                show-size-picker
              ></NPagination>
            </NSpace>
          </NCard>
        </NSpace>
        <edit
          propModal={this.editModal}
          onCloseModal={this.handleModal}
          close-modal={this.handleModal}
          itemData={this.itemData}
          SQLValue={this.sqlForm}
        ></edit>
      </div>
    )
  }
})

export default sqlmanage
